<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>菜单管理</title>
</head>
<body>
<div class="col-md-12">
    <div class="panel panel-default">
        <div class="panel-title">
            菜单信息列表
        </div>
        <div class="panel-body table-responsive">
            <table id="myTable" class="table display"></table>
        </div>
    </div>
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">编辑菜单信息</h4>
            </div>
            <div class="modal-body">
                <!-- Start Row -->
                <div class="row">

                    <div class="form-horizontal">
                        <div :class="clazz.menuNameClazz">
                            <label for="menuName" class="col-sm-2 control-label form-label">菜单名</label>
                            <div class="col-sm-9">
                                <input @change="initClazz($event)" type="text" class="form-control" id="menuName" placeholder="XX功能菜单" v-model="menuName" />
                            </div>
                        </div>
                        <div class="form-group" v-if="parentMenus">
                            <label for="parentMenuId" class="col-sm-2 control-label form-label">上级菜单</label>
                            <div class="col-sm-9">
                                <select v-model="parentMenuId" class="selectpicker form-control" id="parentMenuId">
                                    <option value="-1">--主菜单--</option>
                                    <option v-for="pmenu in parentMenus" :value="pmenu.menuId">{{pmenu.menuName}}</option>
                                </select>
                            </div>
                        </div>
                        <div :class="clazz.faIconClazz" v-if="parentMenuId==-1">
                            <label for="faIcon" class="col-sm-2 control-label form-label">fa图标</label>
                            <div class="col-sm-9">
                                <input @change="initClazz($event)" type="text" class="form-control" id="faIcon" placeholder="fa-icon" v-model="faIcon" />
                            </div>
                        </div>
                        <div :class="clazz.menuUrlClazz">
                            <label for="menuUrl" class="col-sm-2 control-label form-label">菜单地址</label>
                            <div class="col-sm-9">
                                <input @change="initClazz($event)" type="text" class="form-control" id="menuUrl" placeholder="/you/url/pagename" v-model="menuUrl" />
                            </div>
                        </div>
                        <div :class="clazz.menuOrderClazz">
                            <label for="menuOrder" class="col-sm-2 control-label form-label">序号</label>
                            <div class="col-sm-9">
                                <input @change="initClazz($event)" type="number" class="form-control" id="menuOrder" placeholder="88" v-model="menuOrder" />
                            </div>
                        </div>
                    </div>

                </div>
                <!-- End Row -->
            </div>
            <div class="modal-footer" style="margin-top: 0px">
                <button type="button" class="btn btn-white" data-dismiss="modal">关闭</button>
                <button id="saveMenuBtn" @click="saveMenu()" type="button" class="btn btn-default">保存</button>
            </div>
        </div>
    </div>
</div>
<!-- End Moda Code -->

<script>
    $(function() {
        var defOrder = [0, 'asc']; //默认排序列 mark一下，要记得改
        var _table = $('#myTable').DataTable({
            dom: '<"top"Blf<"clear">>rt<"bottom"ip<"clear">>',
            // dom: 'Bfrtip',
            lengthMenu: [10, 25, 50, 75, 100],
            pageLength: 10,
            language: dtlanguage,//中文
            select: true,
            ordering: true,
            order: [defOrder],//表示初期第n列降序排序，使用thymeleaf一定要把双中括号分开写
            processing: true,
            serverSide: true,
            ajax: {
                url: '/service/sysMenu/queryPage',
                type: 'post',
                contentType: "application/json;charset=UTF-8",
                dataType: 'json',
                // 传给服务器的数据，可以添加我们自己的查询参数
                data: function (param) {
                    var orderBy = '';
                    if (param.order != null && param.order.length > 0) {
                        param.order.forEach((o, i) => {
                            orderBy += param.columns[o.column].data + " " + o.dir + ",";
                        });
                        orderBy = orderBy.substring(0, orderBy.length - 1);
                    }
                    var data = {
                        draw: param.draw,
                        search: param.search.value,
                        limit: param.length,
                        offset: param.start,
                        orderBy: orderBy
                    }
                    //当请求需要传递JSON数据格式的参数时，前台应该在JS中使用JSON.stringify()方法，将JSON数据转换成String类型
                    return JSON.stringify(data);
                },
                //预先处理服务器端返回的数据，修改成DT能用格式 draw、recordsTotal、recordsFiltered、data。
                dataFilter: function (text, type) {
                    if (!isEmpty(text)) {
                        var json = JSON.parse(text);//字符串转json
                        if (json.success) {
                            var qbean = json.data;
                            var data = {
                                draw: json.code,
                                recordsTotal: qbean.total,
                                recordsFiltered: qbean.total,
                                data: qbean.list
                            }
                            text = JSON.stringify(data);//json转字符串
                        }
                    }
                    return text;//返回字符串
                },
                //用于处理服务器端返回的数据。 dataSrc是DataTable特有的
                dataSrc: function (data) {
                    if (data.data == null) {
                        return '';
                    } else {
                        return data.data;
                    }
                }
            },
            buttons:[
                {
                    text:'<i class="fa fa-plus"></i>添加菜单',
                    className:'btn btn-square btn-success',
                    action: function (e, dt, node, config) {
                        myFormApp.initData();//清空表单
                        $('#myModal').modal('show');
                    }
                },{
                    text:'<i class="fa fa-trash-o"></i>删除菜单',
                    className:'btn btn-square btn-danger',
                    action: function (e, dt, node, config) {
                        var datas = dt.rows('.selected').data();
                        if(datas!=null && datas.length>0) {
                            swal({
                                    title: "你确定要批量删除菜单吗?",
                                    text: "菜单删除后，将无法使用使用该页功能！",
                                    type: "warning",
                                    showCancelButton: true,
                                    confirmButtonText: "确定",
                                    cancelButtonText: "取消"
                                },
                                function(isConfirm){
                                    if (isConfirm) {
                                        var menuIds = [], isParentMenu=false;
                                        datas.each((d, i) => {
                                            menuIds.push(d.menuId);
                                            if(!isParentMenu && d.parentMenuId.startsWith('fa-'))isParentMenu=true;
                                        });
                                        put('/service/sysMenu/removeList', function (result) {
                                            if(result.success){
                                                spop({
                                                    template: '批量删除菜单成功',
                                                    autoclose: 5000,
                                                    style:'success'
                                                });
                                                _table.ajax.reload(null, false);//刷新列表
                                                if(isParentMenu)myFormApp.getParentMenus();
                                            }else {
                                                spop(result.message, 'error');
                                            }
                                        }, menuIds);
                                    }
                                });
                        }else{
                            spop({
                                template: '请选择要执行删除的行',
                                autoclose: 5000,
                                style:'warning'
                            })
                        }
                    }
                }
            ],
            rowId: 'menuId',
            columns: [
                {
                    data: 'menuOrder',
                    title: '序号',
                    defaultContent: '--',
                    orderable: true
                },{
                    data: 'menuName',
                    title: '菜单名',
                    defaultContent: '--',
                    orderable: true
                },{
                    data: 'parentMenuId',
                    title: '菜单图标',
                    defaultContent: '--',
                    render:function (data, type, row, meta) {
                        if(data.startsWith('fa-'))
                            return '<i style="font-size: 19px;" class="fa '+data+'"></i>';
                        else
                            return '--';
                    }
                },{
                    data: 'menuUrl',
                    title: '菜单地址',
                    defaultContent: '--',
                    orderable: true
                },{
                    data: 'modifyTime',
                    title: '修改时间',
                    defaultContent: '--',
                    orderable: true
                }, {
                    data: 'createTime',
                    title: '创建时间',
                    defaultContent: '--',
                    orderable: true
                }
            ],
            columnDefs: [
                {
                    targets: 6,//最后一列 从0开始  mark一下，要记得改
                    title: '操作',
                    orderable: false,
                    render: function (data, type, row, meta) {
                        return [
                            '<button type="button" class="edit-btn btn btn-info btn-icon" data-menuid="' + row.menuId + '"><i class="fa fa-edit"></i></button>&nbsp;&nbsp;',
                            '<button type="button" class="del-btn btn btn-danger btn-icon" data-menuid="' + row.menuId + '" data-parentmenuid="'+row.parentMenuId+'"><i class="fa fa-trash-o"></i></button>'
                        ].join('');
                    }
                }
            ]
        });

        //方法
        var methods = {
            //保存菜单信息
            saveMenu:function () {
                if(isEmpty(this.menuName)){
                    spop("菜单名不能为空", 'error');
                    this.$set(this.clazz,'menuNameClazz','form-group has-error');
                    return;
                }
                if(this.menuName.length>32){
                    spop("菜单名过长", 'error');
                    this.$set(this.clazz,'menuNameClazz','form-group has-error');
                    return;
                }
                if(this.parentMenuId==-1){//一级菜单需要填写 fa图标
                    if(isEmpty(this.faIcon)){
                        spop("菜单图标不能为空", 'error');
                        this.$set(this.clazz,'faIconClazz','form-group has-error');
                        return;
                    }
                    if(this.faIcon.length>16 || !this.faIcon.startsWith('fa-')){
                        spop("fa图标格式有问题", 'error');
                        this.$set(this.clazz,'faIconClazz','form-group has-error');
                        return;
                    }
                }else{//子菜单需要写地址
                    if(isEmpty(this.menuUrl)){
                        spop("菜单地址不能为空", 'error');
                        this.$set(this.clazz,'menuUrlClazz','form-group has-error');
                        return;
                    }
                    if(this.menuUrl.length>512){
                        spop("菜单地址过长", 'error');
                        this.$set(this.clazz,'menuUrlClazz','form-group has-error');
                        return;
                    }
                }
                if(isEmpty(this.menuOrder)){
                    spop("序号不能为空", 'error');
                    this.$set(this.clazz,'menuOrderClazz','form-group has-error');
                    return;
                }

                var _this = this;
                put('/service/sysMenu/editOne',function (result) {
                    if(result.success) {
                        spop({
                            template: '保存成功',
                            autoclose: 5000,
                            style:'success'
                        });
                        _table.ajax.reload(null, false);//刷新列表
                        if(_this.parentMenuId==-1)_this.getParentMenus();//添加的是一级菜单，需要刷新选择器
                        $('#myModal').modal('hide');
                    }else {
                        spop(result.message, 'error');
                    }
                },{
                    menuId: _this.menuId,
                    menuName: _this.menuName,
                    menuUrl: _this.menuUrl,
                    parentMenuId: _this.parentMenuId==-1?_this.faIcon:_this.parentMenuId,
                    menuOrder: _this.menuOrder
                });
            },
            //初始化输入框样式 change时调用
            initClazz:function (event) {
                var id = event.target.id;
                if(this.clazz[id+'Clazz']!=='form-group'){
                    this.$set(this.clazz, id+'Clazz', 'form-group');
                }
            },
            //初始化表单
            initData:function () {
                this.$set(this,'clazz',{
                    menuNameClazz:'form-group',
                    menuUrlClazz:'form-group',
                    menuOrderClazz:'form-group',
                    faIconClazz:'form-group'
                });
                this.$set(this,'menuId',null);
                this.$set(this,'menuName',null);
                this.$set(this,'parentMenuId',-1);
                this.$set(this,'menuUrl',null);
                this.$set(this,'faIcon',null);
                this.$set(this,'menuOrder',null);
            },
            //获取一级菜单 初始化选择器
            getParentMenus:function () {
                get('/service/sysMenu/getParentMenu',function (result) {
                    if(result.success && result.data){
                        Vue.set(myFormApp, 'parentMenus', result.data);
                    }else {
                        spop(result.message, 'error');
                    }
                })
            }
        }
        //表单vue
        var myFormApp = new Vue({
            el:'#myModal',
            //属性
            data:{
                clazz:{
                    menuNameClazz:'form-group',
                    menuUrlClazz:'form-group',
                    menuOrderClazz:'form-group',
                    faIconClazz:'form-group'
                },
                menuId:null,
                menuName:null,
                parentMenuId:-1,
                parentMenus:null,
                menuUrl:null,
                faIcon:null,
                menuOrder:null
            },
            methods: methods,
            mounted:function () {
                this.getParentMenus();
            },
            updated: function () {}
        });


        //编辑
        $('#myTable tbody').on('click', 'button.edit-btn', function () {
            myFormApp.initData();//清空表单
            var menuId = $(this).data('menuid');
            get('/service/sysMenu/getOne',function (result) {
                if(result.success && result.data){
                    var menu = result.data;
                    Vue.set(myFormApp,'menuId',menuId);
                    Vue.set(myFormApp,'menuName',menu.menuName);
                    Vue.set(myFormApp,'parentMenuId',menu.parentMenuId.startsWith('fa-')?-1:menu.parentMenuId);
                    Vue.set(myFormApp,'faIcon',menu.parentMenuId.startsWith('fa-')?menu.parentMenuId:null);
                    Vue.set(myFormApp,'menuUrl',menu.menuUrl);
                    Vue.set(myFormApp,'menuOrder',menu.menuOrder);
                }else {
                    spop(result.message,'error')
                }
            },{
                menuId: menuId
            });

            $('#myModal').modal('show');
        });

        //删除
        $('#myTable tbody').on('click', 'button.del-btn', function () {
            var menuId = $(this).data('menuid');
            var parentmenuid = $(this).data('parentmenuid');
            swal({
                    title: "你确定要删除菜单吗?",
                    text: "菜单删除后，将无法使用使用该页功能！",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonText: "确定",
                    cancelButtonText: "取消"
                },
                function(isConfirm){
                    if (isConfirm) {
                        del('/service/sysMenu/removeOne/'+menuId,function (result) {
                            if(result.success){
                                spop({
                                    template: '菜单删除成功',
                                    autoclose: 5000,
                                    style:'success'
                                });
                                _table.ajax.reload(null, false);//刷新列表
                                if(parentmenuid.startsWith('fa-'))myFormApp.getParentMenus();
                            }else {
                                spop(result.message, 'error');
                            }
                        })
                    }
                });
        });

    });
</script>
</body>
</html>